// Copyright (c) 2022 NetEase, Inc. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.

package com.netease.yunxin.app.im.message;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.netease.yunxin.kit.alog.ALog;
import com.netease.yunxin.kit.chatkit.model.IMMessageInfo;
import com.netease.nimlib.sdk.v2.message.attachment.V2NIMMessageAttachment;
import com.zhht.htzx.R;
import com.netease.yunxin.kit.chatkit.ui.databinding.ChatBaseMessageViewHolderBinding;
import com.netease.yunxin.kit.chatkit.ui.view.message.viewholder.ChatBaseMessageViewHolder;

import java.util.List;
import android.view.ViewGroup;

/**
 * 商品消息ViewHolder
 */
public class ProductMessageViewHolder extends ChatBaseMessageViewHolder {

    private static final String TAG = "ProductMessageViewHolder";

    private Context context;
    private int viewType;
    private View productItemView; // 商品消息的根视图
    private ImageView productImage;
    private TextView productName;
    private TextView productDesc;
    private TextView productPrice;
    private Button productLinkButton;

    public ProductMessageViewHolder(@NonNull ChatBaseMessageViewHolderBinding parent, int viewType) {
        super(parent, viewType);

        ALog.d(TAG, "=== ProductMessageViewHolder constructor called ===");
        ALog.d(TAG, "viewType: " + viewType);
        ALog.d(TAG, "parent binding: " + (parent != null ? "not null" : "null"));
        ALog.d(TAG, "itemView: " + (itemView != null ? itemView.getClass().getName() : "null"));

        // 获取Context
        this.context = parent.getRoot().getContext();
        this.viewType = viewType;

        ALog.d(TAG, "Context: " + (context != null ? "not null" : "null"));

        // 注意：不在这里创建商品消息布局，而是在addViewToMessageContainer中创建
        // 这样可以避免视图复用时的冲突问题
        
        ALog.d(TAG, "=== ProductMessageViewHolder constructor completed ===");
    }

    /**
     * 创建商品消息布局
     */
    private void createProductLayout() {
        ALog.d(TAG, "=== createProductLayout called ===");
        
        try {
            // 根据viewType选择布局
            int layoutId = getLayoutId();
            ALog.d(TAG, "使用布局ID: " + layoutId);
            
            // 创建商品消息的根视图
            productItemView = LayoutInflater.from(context).inflate(layoutId, null);
            ALog.d(TAG, "商品消息根视图创建成功: " + productItemView.getClass().getName());
            
            // 初始化视图组件
            initViews();
            
        } catch (Exception e) {
            ALog.e(TAG, "createProductLayout error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 初始化视图组件
     */
    private void initViews() {
        ALog.d(TAG, "=== initViews called ===");
        
        if (productItemView == null) {
            ALog.e(TAG, "productItemView is null, cannot init views");
            return;
        }
        
        try {
            // 使用商品消息的根视图来查找组件
            View rootView = productItemView;
            
            productImage = rootView.findViewById(R.id.product_image);
            productName = rootView.findViewById(R.id.product_name);
            productDesc = rootView.findViewById(R.id.product_desc);
            productPrice = rootView.findViewById(R.id.product_price);
            productLinkButton = rootView.findViewById(R.id.product_link_button);
            

            ALog.d(TAG, "Views initialized: " + 
                "productImage=" + (productImage != null) + 
                ", productName=" + (productName != null) + 
                ", productDesc=" + (productDesc != null) + 
                ", productPrice=" + (productPrice != null) +
                ", productLinkButton=" + (productLinkButton != null));
                
            if (productImage == null || productName == null || productDesc == null || productPrice == null) {
                ALog.d(TAG, "某些视图组件为null，可能布局文件有问题");
                ALog.d(TAG, "当前布局根视图: " + rootView.getClass().getName());
            }
            
            // 为测试按钮设置点击事件
            rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ALog.d(TAG, "=== 测试按钮被点击 ===");
                    Toast.makeText(context, "测试按钮点击成功！", Toast.LENGTH_LONG).show();
                }
            });
            ALog.d(TAG, "测试按钮点击事件设置完成");

            // 检查按钮状态
            if (productLinkButton != null) {
                ALog.d(TAG, "商品链接按钮状态检查:");
                ALog.d(TAG, "  - 是否可点击: " + productLinkButton.isClickable());
                ALog.d(TAG, "  - 是否可获得焦点: " + productLinkButton.isFocusable());
                ALog.d(TAG, "  - 是否启用: " + productLinkButton.isEnabled());
                ALog.d(TAG, "  - 是否可见: " + (productLinkButton.getVisibility() == View.VISIBLE));
            }
            
        } catch (Exception e) {
            ALog.e(TAG, "initViews error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 绑定数据
     */
    public void bindData(IMMessageInfo messageInfo, int position) {
        ALog.d(TAG, "=== bindData called ===");
        ALog.d(TAG, "position: " + position);
        ALog.d(TAG, "messageInfo: " + (messageInfo != null ? "not null" : "null"));
        
        try {
            if (messageInfo == null) {
                ALog.e(TAG, "messageInfo is null");
                return;
            }
            
            // 确保商品消息视图已经创建
            if (productItemView == null) {
                ALog.e(TAG, "productItemView is null, cannot bind data");
                return;
            }
            
            ALog.d(TAG, "Message attachment: " + (messageInfo.getMessage().getAttachment() != null ?
                messageInfo.getMessage().getAttachment().getClass().getName() : "null"));

            // 安全地获取商品附件
            ProductAttachment attachment = null;
            Object rawAttachment = messageInfo.getMessage().getAttachment();
            
            if (rawAttachment instanceof ProductAttachment) {
                // 直接转换
                attachment = (ProductAttachment) rawAttachment;
                ALog.d(TAG, "Attachment is already ProductAttachment type");
            } else if (rawAttachment != null) {
                // 尝试从原始数据创建 ProductAttachment
                ALog.d(TAG, "Attachment is not ProductAttachment type, trying to create from raw data");
                ALog.d(TAG, "Attachment class: " + rawAttachment.getClass().getName());
                
                try {
                    // 获取原始JSON数据
                    String rawData = null;
                    if (rawAttachment instanceof V2NIMMessageAttachment) {
                        rawData = ((V2NIMMessageAttachment) rawAttachment).getRaw();
                    }
                    
                    ALog.d(TAG, "Raw attachment data: " + rawData);
                    
                    if (rawData != null && !rawData.trim().isEmpty()) {
                        // 创建新的 ProductAttachment 并解析数据
                        attachment = new ProductAttachment();
                        attachment.parseDataFromString(rawData);
                        ALog.d(TAG, "Successfully created ProductAttachment from raw data");
                    } else {
                        ALog.e(TAG, "Raw attachment data is null or empty");
                    }
                } catch (Exception e) {
                    ALog.e(TAG, "Failed to create ProductAttachment from raw data: " + e.getMessage());
                    e.printStackTrace();
                }
            }
            
            if (attachment == null) {
                ALog.e(TAG, "ProductAttachment is null, cannot bind data");
                return;
            }
            
            ALog.d(TAG, "ProductAttachment found: " + attachment.toString());

            // 设置商品信息
            if (productName != null) {
                productName.setText(attachment.getProductName());
                ALog.d(TAG, "设置商品名称: " + attachment.getProductName());
            }
            
            if (productDesc != null) {
                productDesc.setText(attachment.getProductDesc());
                ALog.d(TAG, "设置商品描述: " + attachment.getProductDesc());
            }
            
            if (productPrice != null) {
                productPrice.setText(attachment.getProductPrice());
                ALog.d(TAG, "设置商品价格: " + attachment.getProductPrice());
            }

            // 加载商品图片
            if (productImage != null) {
                if (attachment.getProductImage() != null && !attachment.getProductImage().isEmpty()) {
                    ALog.d(TAG, "加载商品图片: " + attachment.getProductImage());
                    Glide.with(context)
                        .load(attachment.getProductImage())
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher)
                        .into(productImage);
                } else {
                    ALog.d(TAG, "使用默认商品图片");
                    productImage.setImageResource(R.mipmap.ic_launcher);
                }
            }

            // 设置商品链接按钮点击事件
            if (productLinkButton != null) {
                ALog.d(TAG, "设置商品链接按钮点击事件");
                productLinkButton.setClickable(true);
                productLinkButton.setFocusable(true);
                productLinkButton.setEnabled(true);
                
                // 先设置一个简单的测试点击事件
                productLinkButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ALog.d(TAG, "=== 商品链接按钮被点击 - 测试 ===");
                        Toast.makeText(context, "商品链接按钮测试点击成功！", Toast.LENGTH_LONG).show();
                    }
                });
                
                // 添加触摸监听器来调试
                productLinkButton.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, android.view.MotionEvent event) {
                        ALog.d(TAG, "商品链接按钮触摸事件: " + event.getAction() + ", x=" + event.getX() + ", y=" + event.getY());
                        return false; // 不消费事件，让onClick处理
                    }
                });
                
                ALog.d(TAG, "商品链接按钮点击事件设置完成");
                
            } else {
                ALog.e(TAG, "productLinkButton 为 null，无法设置点击事件");
            }

            // 设置整个商品消息的点击事件
            View rootView = productItemView;
            ProductAttachment finalAttachment = attachment;
            rootView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ALog.d(TAG, "=== 商品消息根视图被点击 ===");
                    Toast.makeText(context, "商品消息被点击！", Toast.LENGTH_SHORT).show();
                    onProductClick(finalAttachment);
                }
            });
            
            // 确保根视图可以接收点击事件
            rootView.setClickable(true);
            rootView.setFocusable(true);
            
            // 添加触摸监听器来调试根视图
            rootView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, android.view.MotionEvent event) {
                    ALog.d(TAG, "商品消息根视图触摸事件: " + event.getAction() + ", x=" + event.getX() + ", y=" + event.getY());
                    return false; // 不消费事件，让onClick处理
                }
            });

            ALog.d(TAG, "=== bindData completed successfully ===");

        } catch (Exception e) {
            ALog.e(TAG, "bindData error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 商品点击事件
     */
    private void onProductClick(ProductAttachment attachment) {
        ALog.d(TAG, "=== onProductClick called ===");
        
        try {
            // 显示商品详情
            ALog.d(TAG, "显示商品详情");
            showProductDetail(attachment);
        } catch (Exception e) {
            ALog.e(TAG, "onProductClick error: " + e.getMessage());
            Toast.makeText(context, "显示商品详情失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 显示商品详情
     */
    private void showProductDetail(ProductAttachment attachment) {
        StringBuilder detail = new StringBuilder();
        detail.append("商品ID: ").append(attachment.getProductId()).append("\n");
        detail.append("商品名称: ").append(attachment.getProductName()).append("\n");
        detail.append("商品价格: ").append(attachment.getProductPrice()).append("\n");
        detail.append("商品描述: ").append(attachment.getProductDesc());

        Toast.makeText(context, detail.toString(), Toast.LENGTH_LONG).show();
    }

    /**
     * 处理布局文件中定义的按钮点击事件
     */
    public void onProductLinkButtonClick(View view) {
        ALog.d(TAG, "=== 布局文件定义的按钮点击事件被触发 ===");
        Toast.makeText(context, "布局文件按钮点击成功！", Toast.LENGTH_LONG).show();
    }

    /**
     * 获取布局ID
     */
    public int getLayoutId() {
        ALog.d(TAG, "=== getLayoutId called ===");
        ALog.d(TAG, "viewType: " + viewType);
        
        // 根据 viewType 返回不同的布局
        if (viewType == 1) { // VIEW_TYPE_SELF
            ALog.d(TAG, "返回自己的布局: item_product_message_self");
            return R.layout.item_product_message_self;
        } else {
            ALog.d(TAG, "返回他人的布局: item_product_message");
            return R.layout.item_product_message;
        }
    }

    /**
     * 重写父类方法，添加商品消息视图到消息容器中
     * 这是关键方法，确保商品消息能够正确显示
     */
    @Override
    protected void addViewToMessageContainer() {
        ALog.d(TAG, "=== addViewToMessageContainer called ===");
        
        try {
            // 获取消息容器
            ViewGroup messageContainer = getMessageContainer();
            if (messageContainer == null) {
                ALog.e(TAG, "messageContainer is null");
                return;
            }
            
            // 检查消息容器是否已经有商品消息视图
            if (messageContainer.getChildCount() == 0) {
                // 消息容器为空，需要创建新的商品消息视图
                ALog.d(TAG, "Message container is empty, creating new product view");
                createProductLayout();
                
                if (productItemView != null) {
                    messageContainer.addView(productItemView);
                    ALog.d(TAG, "Added new product view to container");
                }
            } else {
                // 消息容器已经有视图，检查是否是商品消息视图
                View existingView = messageContainer.getChildAt(0);
                if (existingView != productItemView) {
                    ALog.d(TAG, "Container has different view, replacing it");
                    messageContainer.removeAllViews();
                    createProductLayout();
                    if (productItemView != null) {
                        messageContainer.addView(productItemView);
                    }
                } else {
                    ALog.d(TAG, "Container already has correct product view");
                }
            }
            
            // 调用bindData方法绑定数据
            if (currentMessage != null) {
                ALog.d(TAG, "Calling bindData with currentMessage");
                bindData(currentMessage.getMessageData(), position);
            } else {
                ALog.e(TAG, "currentMessage is null, cannot bind data");
            }
            
        } catch (Exception e) {
            ALog.e(TAG, "addViewToMessageContainer error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}